package com.zy.activity.receive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import zy.dto.base.emp.EmpLoginDto;
import zy.entity.sell.cart.T_Sell_Cart;
import zy.entity.sell.cart.T_Sell_CartList;
import zy.entity.vip.member.T_Vip_Member;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.zy.R;
import com.zy.activity.BaseActivity;
import com.zy.activity.product.ProductActivity;
import com.zy.activity.vip.MemberAddActivity;
import com.zy.adapter.receive.CartListAdapter;
import com.zy.api.sell.CartAPI;
import com.zy.api.vip.MemberAPI;
import com.zy.util.ActivityUtil;
import com.zy.util.CacheVipMemberUtil;
import com.zy.util.CommonParam;
import com.zy.util.Constants;
import com.zy.util.ImageUtil;
import com.zy.view.dialog.InputDialog;
import com.zy.view.dialog.WarnTipDialog;
import com.zy.view.dialog.popup.BottomPopup;
import com.zy.view.zxing.CaptureActivity;

public class ReceiveActivity extends BaseActivity implements OnClickListener{
	private Handler handler;
	private ImageView img_back,img_right,iv_vm_img;
	private TextView tv_register,tv_isvip,tv_shopcart,tv_vm_name,tv_consume_info,tv_icon_next;
	private TextView tv_cart_amount,tv_cart_money;
	private ListView listView;
	private CartListAdapter cartListAdapter;
	private LinearLayout ll_btn;
	private RelativeLayout rl_member;
	private Button btn_add_product,btn_save,btn_finish;
	
	private CartAPI cartAPI;
	private MemberAPI memberAPI;
	private T_Vip_Member member;
	private List<T_Sell_CartList> cartLists = new ArrayList<T_Sell_CartList>();
	private static final int SUCC_STATE_DOWNLOADIMG = 3;
	private int delPosition = -1;
	private InputDialog inputDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_receive);
		initView();
		initData();
		initListener();
		initHandle();
		listCartList();
		member = CacheVipMemberUtil.getMember();
		if(member == null){
			ll_btn.setVisibility(View.VISIBLE);
			rl_member.setVisibility(View.GONE);
		}else {
			ll_btn.setVisibility(View.GONE);
			rl_member.setVisibility(View.VISIBLE);
			initMemberValue();
		}
	}
	
	private void initView(){
		progress = new ProgressDialog(this);
		ll_btn = (LinearLayout)findViewById(R.id.ll_btn);
		rl_member = (RelativeLayout)findViewById(R.id.rl_member);
		tv_shopcart = (TextView)findViewById(R.id.tv_shopcart);
		tv_register = (TextView)findViewById(R.id.tv_register);
		tv_isvip = (TextView)findViewById(R.id.tv_isvip);
		tv_vm_name = (TextView)findViewById(R.id.tv_vm_name);
		tv_consume_info = (TextView)findViewById(R.id.tv_consume_info);
		tv_icon_next = (TextView)findViewById(R.id.tv_icon_next);
		tv_cart_amount = (TextView)findViewById(R.id.tv_cart_amount);
		tv_cart_money = (TextView)findViewById(R.id.tv_cart_money);
		img_back = (ImageView) findViewById(R.id.img_back);
		img_right = (ImageView) findViewById(R.id.img_right);
		iv_vm_img = (ImageView) findViewById(R.id.iv_vm_img);
		img_back.setVisibility(View.VISIBLE);
		img_right.setVisibility(View.VISIBLE);
		img_right.setImageResource(R.drawable.icon_scan);
		tv_shopcart.setTypeface(iconfont);
		tv_register.setTypeface(iconfont);
		tv_isvip.setTypeface(iconfont);
		tv_icon_next.setTypeface(iconfont);
		listView = (ListView)findViewById(R.id.lv_data);
		btn_add_product = (Button)findViewById(R.id.btn_add_product);
		btn_save = (Button)findViewById(R.id.btn_save);
		btn_finish = (Button)findViewById(R.id.btn_finish);
	}
	private void initData() {
		cartAPI = new CartAPI(this);
		memberAPI = new MemberAPI(this);
		cartListAdapter = new CartListAdapter(this, cartLists);
		listView.setAdapter(cartListAdapter);
	}
	private void initListener(){
		img_back.setOnClickListener(this);
		img_right.setOnClickListener(this);
		btn_add_product.setOnClickListener(this);
		btn_save.setOnClickListener(this);
		btn_finish.setOnClickListener(this);
	}
	private void initMemberValue(){
		tv_vm_name.setText(StringUtil.trimString(member.getVm_name())+"("+StringUtil.trimString(member.getVm_mobile())+")");
		StringBuffer info = new StringBuffer();
		info.append("总计消费"+StringUtil.trimString(member.getVm_total_money())+"元，");
		if(StringUtil.isNotEmpty(member.getVm_lastbuy_date())){
			info.append("<font color=\"#ff0000\">").append(DateUtil.getDaysBetween(member.getVm_lastbuy_date(), DateUtil.getYearMonthDate())).append("</font>天未消费");
		}else {
			info.append("<font color=\"#ff0000\">").append(DateUtil.getDaysBetween(member.getVm_date(), DateUtil.getYearMonthDate())).append("</font>天未消费");
		}
		tv_consume_info.setText(Html.fromHtml(info.toString()));
		if(StringUtil.isNotEmpty(member.getVm_img_path())){
			cartAPI.loadImg(CommonParam.file_url+member.getVm_img_path(), handler, SUCC_STATE_DOWNLOADIMG);
		}else {
			iv_vm_img.setImageResource(R.drawable.nophoto);
		}
	}
	@SuppressLint("HandlerLeak")
	private void initHandle(){
		handler = new Handler() {
			@SuppressWarnings("unchecked")
			public void handleMessage(Message msg) {
				if(progress != null && progress.isShowing()){
					progress.dismiss();
				}
				switch (msg.what) {
					case R.id.rl_isvip:
						if(msg.obj == null){
							ActivityUtil.showShortToast(ReceiveActivity.this, "查不到会员信息");
							return;
						}
						member = (T_Vip_Member)msg.obj;
						CacheVipMemberUtil.putMember(member);
						ll_btn.setVisibility(View.GONE);
						rl_member.setVisibility(View.VISIBLE);
						initMemberValue();
						inputDialog.dismiss();
						if (cartLists.size() > 0) {
							updateCartListVip();
						}
						break;
					case SUCC_STATE_DOWNLOADIMG:
						if(msg.obj != null){
							Bitmap bitmap_img = (Bitmap)msg.obj;
							iv_vm_img.setImageBitmap(ImageUtil.getCircleBitmap(bitmap_img));
						}
						break;
					case STATE_LOAD:
						if(msg.obj == null){
							return;
						}
						cartLists.clear();
						cartLists.addAll((List<T_Sell_CartList>)msg.obj);
						cartListAdapter.notifyDataSetChanged();
						calcAmountMoney();
						break;
					case STATE_UPDATE:
						ActivityUtil.showShortToast(ReceiveActivity.this, "修改成功");
						calcAmountMoney();
						break;
					case STATE_DELETE:
						ActivityUtil.showShortToast(ReceiveActivity.this, "删除成功");
						cartLists.remove(delPosition);
						cartListAdapter.notifyDataSetChanged();
						calcAmountMoney();
						break;
					case R.id.btn_save:
						ActivityUtil.showShortToast(ReceiveActivity.this, "下单成功，请到前台收银结算");
						CacheVipMemberUtil.clear();
						ActivityUtil.start_Activity(ReceiveActivity.this, ReceiveIndexActivity.class,new BasicNameValuePair(Constants.TITLE, "接待顾客"));
						ActivityUtil.finish(ReceiveActivity.this);
						break;
					case R.id.btn_finish:
						ActivityUtil.showShortToast(ReceiveActivity.this, "成功结束接待");
						CacheVipMemberUtil.clear();
						ActivityUtil.start_Activity(ReceiveActivity.this, ReceiveIndexActivity.class,new BasicNameValuePair(Constants.TITLE, "接待顾客"));
						ActivityUtil.finish(ReceiveActivity.this);
						break;
					case STATE_ERROR:
						String message = null;
						if(msg.obj != null){
							message = msg.obj.toString();
						}
						ActivityUtil.showShortToast(ReceiveActivity.this, message);
						break;
				}
				super.handleMessage(msg);
			}
		};
	}
	private void listCartList(){
		Map<String, Object> params = new HashMap<String,Object>();
		EmpLoginDto user = getUser();
		params.put(CommonUtil.COMPANYID, user.getCompanyid());
		params.put("scl_em_code", user.getEm_code());
		params.put("scl_shop_code", user.getEm_shop_code());
		cartAPI.listCartList(params, handler, STATE_LOAD);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:
			ActivityUtil.finish(ReceiveActivity.this);
			break;
		case R.id.img_right:
			Intent intent = new Intent(ReceiveActivity.this, CaptureActivity.class);
			startActivityForResult(intent, REQUEST_CODE_SCANNER);
			break;
		case R.id.btn_add_product:
			Bundle bundle = new Bundle();
			bundle.putString(Constants.TITLE, "查询商品");
			ActivityUtil.start_ActivityForResult(ReceiveActivity.this, ProductActivity.class, REQUEST_CODE_CHOOSE, bundle);
			break;
		case R.id.btn_save:
			saveCart();
			break;
		case R.id.btn_finish:
			clearCartList();
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if(requestCode == REQUEST_CODE_CHOOSE){//选择商品
				listCartList();
			}
			if(requestCode == REQUEST_CODE_ADD){//注册会员
				member = (T_Vip_Member)data.getSerializableExtra("member");
				CacheVipMemberUtil.putMember(member);
				ll_btn.setVisibility(View.GONE);
				rl_member.setVisibility(View.VISIBLE);
				initMemberValue();
				if (cartLists.size() > 0) {
					updateCartListVip();
				}
			}
			if(requestCode == REQUEST_CODE_SCANNER){//扫一扫
				String code = data.getStringExtra("code");
				Bundle bundle = new Bundle();
				bundle.putString(Constants.TITLE, "查询商品");
				bundle.putString("barcode", code);
				bundle.putSerializable("member", member);
				ActivityUtil.start_ActivityForResult(ReceiveActivity.this, ProductActivity.class, REQUEST_CODE_CHOOSE, bundle);
			}
		}
	}
	
	public void onVipClick(View v) {
		switch (v.getId()) {
		case R.id.rl_isvip:
			if(inputDialog == null){
				inputDialog = new InputDialog(ReceiveActivity.this, "输入手机号或会员卡号");
		        inputDialog.getOkButton().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						String vm_cardcode = inputDialog.getInputValue();
						if(StringUtil.isEmpty(vm_cardcode)){
							ActivityUtil.showShortToast(ReceiveActivity.this, "请输入手机号或会员卡号");
							return;
						}
						Map<String, Object> params = buildBaseParam();
						params.put("vm_cardcode", vm_cardcode);
						memberAPI.search(params, handler, R.id.rl_isvip);
					}
				});
			}
	        inputDialog.show();
			break;
		case R.id.rl_register:
			Bundle bundle = new Bundle();
			bundle.putString(Constants.TITLE, "新增会员");
			bundle.putString(Constants.TYPE, "receive");
			ActivityUtil.start_ActivityForResult(ReceiveActivity.this, MemberAddActivity.class, REQUEST_CODE_ADD, bundle);
			break;
		default:
			break;
		}
	}
	
	
	public void calcAmountMoney(){
		int totalAmount = 0;
		double totalMoney = 0d;
		for (T_Sell_CartList item : cartLists) {
			totalAmount += item.getScl_amount();
			totalMoney += item.getScl_amount() * item.getScl_sell_price();
		}
		tv_cart_amount.setText(Html.fromHtml("当前购物车<font color=\"#ff0000\">"+totalAmount+"</font>件"));
		tv_cart_money.setText(Html.fromHtml("合计￥<font color=\"#ff0000\">"+String.format("%.2f", totalMoney)+"</font>元"));
	}
	public void updateAmount(int position){
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("scl_id", cartLists.get(position).getScl_id());
		params.put("scl_amount", cartLists.get(position).getScl_amount());
		cartAPI.updateAmount(params, handler, STATE_UPDATE);
	}
	public void delCartList(final int delPos){
		BottomPopup delPopup = new BottomPopup(this, "是否删除？", new String[]{"删除"});
		delPopup.setItemClickListener(new BottomPopup.onPopupWindowItemClickListener() {
				@Override
				public void onItemClick(int position) {
					delPosition = delPos;
					Map<String, Object> params = new HashMap<String,Object>();
					params.put("scl_id", cartLists.get(delPos).getScl_id());
					cartAPI.delCartList(params, handler, STATE_DELETE);
				}
			});
		delPopup.showView();
	}
	public void clearCartList(){
		final WarnTipDialog warnTipDialog = new WarnTipDialog(this, "确认结束接待？");
		warnTipDialog.setBtnOkLinstener(new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				warnTipDialog.dismiss();
				Map<String, Object> params = buildBaseParam();
				params.put("em_code", getUser().getEm_code());
				progress.show();
				cartAPI.clearCartList(params, handler, R.id.btn_finish);
			}
		});
		warnTipDialog.show();
	}
	public void updateCartListVip(){
		Map<String, Object> params = buildBaseParam();
		params.put("em_code", getUser().getEm_code());
		params.put("vm_code", member.getVm_code());
		cartAPI.updateCartListVip(params, handler, -1);
	}
	public void saveCart(){
		if(cartLists.size() == 0){
			ActivityUtil.showShortToast(ReceiveActivity.this, "请选择商品");
			return;
		}
		Map<String, Object> params = buildBaseParam();
		T_Sell_Cart cart = new T_Sell_Cart();
		EmpLoginDto user = getUser();
		cart.setSc_em_code(user.getEm_code());
		cart.setSc_shop_code(user.getEm_shop_code());
		cart.setCompanyid(user.getCompanyid());
		params.put("cart", JSON.toJSONString(cart));
		progress.show();
		cartAPI.saveCart(params, handler, R.id.btn_save);
	}
	
}
